<template>
  <BasicModal
    v-bind="$attrs"
    width="600px"
    :title="title"
    :cancelButtonProps="{
      preIcon: 'ant-design:close-outlined',
    }"
    :okButtonProps="{
      disabled,
      preIcon: 'ant-design:save-outlined',
    }"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
    @visibleChange="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm :disabled="disabled" @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';
  import { schemas } from '../data';
  import { nutritionAddApi, nutritionUpdateApi } from '@/api/jiankang/nutrition';
  import { getAuthCache } from '@/utils/auth';
  import { USER_INFO_KEY } from '@/enums/cacheEnum';

  const userInfo = getAuthCache(USER_INFO_KEY);

  const emit = defineEmits(['reload']);
  const title = ref('');
  const disabled = ref(false);
  const { createMessage } = useMessage();
  const [registerForm, { validate, getFieldsValue, resetFields, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });

  const [registerModal, { closeModal }] = useModalInner(({ type, data = {} }) => {
    if (type) {
      resetFields();
      nextTick(() => {
        type === 'edit'
          ? ((title.value = '编辑'), (disabled.value = false))
          : type === 'view'
            ? ((title.value = '查看'), (disabled.value = true))
            : ((title.value = '新增'),
              (disabled.value = false),
              (data.yysUid = (userInfo as any).id));
      });
      console.log(data, '初始化');
      data && setFieldsValue(data);
    }
  });

  function handleVisibleChange(visible) {
    if (!visible) {
      resetFields();
      closeModal();
      emit('reload');
    }
  }

  const handleSubmit = async () => {
    await validate();
    const values = await getFieldsValue();
    if (values.id) {
      await nutritionUpdateApi(values);
      console.log('打印修改数据:', values), createMessage.success('修改成功');
    } else {
      await nutritionAddApi(values);
      console.log('打印修改数据:', values), createMessage.success('添加成功');
    }
    closeModal();
    emit('reload');
  };
  const handleCancel = () => {
    resetFields();
    closeModal();
  };
</script>
